package com.listen.service.DB;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.listen.common.DateFormatUtil;
import com.listen.common.HttpClientProxy;
import com.listen.common.IPProxyNew;
import com.listen.common.SpecialCharacterHandler;
import com.listen.model.Study;
import com.listen.model.User;
import com.listen.vo.HeadParmsVO;

import net.sf.json.JSONObject;

public class Badayuan {
	private static final Logger log = LoggerFactory.getLogger(Badayuan.class);
	private ConcurrentHashMap<String, Object>  resultMap = null;
	private HttpClientProxy instance = new HttpClientProxy();
	private CloseableHttpResponse response = null;
	private CloseableHttpClient httpClient = null;
	private String proxyInfo = null;
	private String _viewstategenerator = null;
	private String _eventvalidation = null;
	private String _viewstate = null;
	private String loginUrl = null;
	private String prefixUrl = null;
	private String cookie = null;
	private String host = null;
	private String origin = null;
	private String referer = null;
	private String userid = null;
	private String info = null;
	private String RID = null;
	private String ids = null;
	private String index = null;
	private String se = null;
	private int nowNum = 0;
	private String __EVENTTARGET = null;
	private String __EVENTARGUMENT = null;
	private String __VIEWSTATE = null;
	private String __VIEWSTATEGENERATOR = null;
			
	
	public static void main(String args[]) throws InterruptedException {
		IPProxyNew proxy = new IPProxyNew(null);
		User user = new User();
		Badayuan instance = new Badayuan();
		user.setAllNum(30);
		user.setCode("130828199004067334");
		user.setPassword("888888");
		user.setZy("2");
		for(int i=20;i<=20;i++) {
			user.setNowNum(i);
			String ip = proxy.getOneIpAndPort();
			System.out.println(ip);
			Map<String,Object> map = instance.listen(user,ip);
			System.out.println(map.get("msg"));
			if(map!=null && "1".equals(map.get("successFlag"))) {
				break;
			}
			Thread.sleep(2000);
			//Thread.sleep(1000);
			//Map<String,Object> map = instance.listen(user,"");
			//System.out.println(map.get("msg"));
		}
	}
	
	//统一听课
	public Map<String,Object> listen(User user,String ip){
		this.nowNum = user.getNowNum();
		this.proxyInfo = ip;
		resultMap = new ConcurrentHashMap<>();
		resultMap.put("successFlag", "0");
		resultMap.put("dayNum", "0");
		resultMap.put("addNum", "0");
		String code = user.getCode();
		if(code==null||code.trim()==""){
			return null;
		}
		try {
			toLoginPage(user);
		} catch (Exception e) {
			log.error(user.getZyName()+"-"+ code +"-第"+user.getNowNum()+"/"+user.getTodayNum()+"节听课异常--->",e);
		}
		return resultMap;
	}
	
	/**
	 * 解析登录页，获取登录参数
	 * @param 	loginurl 登录地址
	 * @param	prefixUrl 路径前缀(根路径)
	 */
	private void toLoginPage(User user){
		this.loginUrl = user.getAddress();
		String zy = user.getZy().substring(0,1);
		if(zy.equals("1"))
			this.index = "";
		else
			this.index = zy;
		if(StringUtils.isBlank(loginUrl)){
			switch(zy){
			case "1": {
				if("10".equals(user.getZy())) {
					user.setZyName("土建施工员");
					this.se = "0";
				}else if("11".equals(user.getZy())) {
					user.setZyName("装饰装修施工员");
					this.se = "1";
				}else if("12".equals(user.getZy())) {
					user.setZyName("设置安装施工员");
					this.se = "2";
				}else if("13".equals(user.getZy())) {
					user.setZyName("市政工程施工员");
					this.se = "3";
				}else {
					log.info("不存在的专业 : " + user.getZy());
					return;
				}
				loginUrl="http://139.199.204.162:8081/Login.aspx?ZY=1";break;
			}
			case "2": {
				user.setZyName("标准员");
				loginUrl="http://139.199.15.78:8081/Login.aspx?ZY=2";break;
			}
			case "3": {
				user.setZyName("材料员");
				loginUrl="http://139.199.64.185:8081/Login.aspx?ZY=3";break;
			}
			case "4": {
				user.setZyName("机械员");
				loginUrl="http://139.199.65.110:8081/Login.aspx?ZY=4";break;
			}
			case "5": {
				user.setZyName("安全员");
				loginUrl="http://139.199.65.98:8081/Login.aspx?ZY=5";break;
			}
			case "6": {
				user.setZyName("资料员");
				loginUrl="http://139.199.65.78:8081/Login.aspx?ZY=6";break;
			}
			case "7": {
				if("70".equals(user.getZy())) {
					user.setZyName("土建质量员");
					this.se = "0";
				}else if("71".equals(user.getZy())) {
					user.setZyName("装饰装修质量员");
					this.se = "1";
				}else if("72".equals(user.getZy())) {
					user.setZyName("设置安装质量员");
					this.se = "2";
				}else if("73".equals(user.getZy())) {
					user.setZyName("市政工程质量员");
					this.se = "3";
				}else {
					log.info("不存在的专业 : " + user.getZy());
					return;
				}
				loginUrl="http://123.207.89.229:8081/Login.aspx?ZY=7";
				break;
			}
			case "8": {
				user.setZyName("劳务员");
				loginUrl="http://139.199.65.78:8082/Login.aspx?ZY=8";
				break;
			}
			}
		}else {
			switch(user.getZy()){
			case "10" :this.se = "0";break;
			case "70" :this.se = "0";break;
			case "11" :this.se = "1";break;
			case "71" :this.se = "1";break;
			case "12" :this.se = "2";break;
			case "72" :this.se = "2";break;
			case "13" :this.se = "3";break;
			case "73" :this.se = "3";break;
			default:this.se = "";break;
			}
		}
		this.referer = loginUrl;
		this.prefixUrl = loginUrl.substring(0,loginUrl.lastIndexOf("/"));
		this.origin = this.prefixUrl;
		this.host = this.origin.substring(this.origin.indexOf("//")+2, this.origin.length());
		try {
			response = instance.sendHttpGet(httpClient,loginUrl, proxyInfo);
			if(response==null||response.getStatusLine()==null) {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() + "-toLoginPage失败--->response="+response);
    			return;
    		}
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state ==302){
				Header[] hearders = response.getHeaders("Set-Cookie");
				String loginCookie = hearders[0].getValue();
				this.cookie = loginCookie.substring(0, loginCookie.indexOf(";"));
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
			    Document document = Jsoup.parse(html);
			    Element parm1 = document.getElementById("__VIEWSTATEGENERATOR");
			    this._viewstategenerator = parm1.attr("value");
			    Element parm2 = document.getElementById("__EVENTVALIDATION");
			    this._eventvalidation = parm2.attr("value");
			    Element parm3 = document.getElementById("__VIEWSTATE");
			    this._viewstate = parm3.attr("value");
			    //log.info(user.getZyName()+"-"+ user.getCode() +" -自动获取登录页面参数成功，开始登录...");
			    login(user);
			}else{
				log.info(user.getZyName()+"-"+ user.getCode() +" -自动获取登录页面参数失败!state="+state);
			}
		} catch (Exception e) {
			log.info(user.getCode()+"-自动获取登录页面参数异常-->",e);
		}finally{
			instance.closeResource(response,httpClient);
		}
	}
	
	public void login(User user) {
		Map<String, String> maps = new HashMap<String, String>();
        maps.put("__VIEWSTATE", this._viewstate); 
        maps.put("__VIEWSTATEGENERATOR",this._viewstategenerator);
        maps.put("__EVENTVALIDATION",this._eventvalidation); 
        maps.put("txtUserName",user.getCode());
        maps.put("txtPwd",user.getPassword());
        maps.put("ddlType", "2");
        if(StringUtils.isNotBlank(se)) {
        	maps.put("se", se);
        }
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
	    HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setCacheControl("max-age=0");
	    heads.setContentType("application/x-www-form-urlencoded");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setOrigin(this.origin);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	try {
    		response = instance.sendHttpPost(httpClient, heads, loginUrl, maps, proxyInfo);
    		if(response==null||response.getStatusLine()==null) {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() + "-login失败--->response="+response);
    			return;
    		}
    		int state = response.getStatusLine().getStatusCode();
    		if(state==200 || state == 302) {
    			Header[] hearders = response.getHeaders("Set-Cookie");
    			if(hearders != null && hearders.length > 1) {
    				String userIdCookie = hearders[0].getValue();
    				String userid = userIdCookie.substring(0, userIdCookie.indexOf(";"));
    				String infoCookies = hearders[1].getValue();
    				String info = infoCookies.substring(0, infoCookies.indexOf(";"));
    				this.info = info;
    				this.userid = userid;
    				resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-login成功--->info="+info);
    				smn_vip(user);
    			}else {
    				resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-login-获取用户信息失败--->info="+info);
    			}
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-login失败--->state="+state);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-login异常");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void smn_vip(User user) {
		String path = this.prefixUrl + "/StudentClass"+index+"/SMN_VIP"+index+".aspx";
		this.cookie = this.cookie + "; "+this.userid +"; "+ this.info;
		
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	try {
			response = instance.sendHttpGet(httpClient, heads, path, this.proxyInfo);
			int status = response.getStatusLine().getStatusCode();
			if(status == 200) {
				this.referer = path;
				resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip 请求成功---->status="+status);
				smn_vip_home_top(user);
			}else{
				resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip 请求失败---->status="+status);
			}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip 请求异常");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void smn_vip_home_top(User user) {
		String path = this.prefixUrl + "/StudentClass"+index+"/SMN_VIP_HOME_TOP"+index+".aspx";
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	try {
    		response = instance.sendHttpGet(httpClient, heads, path, this.proxyInfo);
    		int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
    			this.referer = path;
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip 请求成功---->status="+status);
    			smn_vip_left(user);
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip 请求失败---->status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip_home_top 请求异常");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void smn_vip_left(User user) {
		String path = this.prefixUrl + "/StudentClass"+index+"/SMN_VIP_left"+index+".aspx";
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	try {
    		response = instance.sendHttpGet(httpClient, heads, path, this.proxyInfo);
    		int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
    			this.referer = path;
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip_left 请求成功---->status="+status);
    			shipinCurStudy(user);
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip_left 请求失败---->status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-smn_vip_left 请求异常");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void shipinCurStudy(User user) {
		String path = this.prefixUrl + "/StudentClass"+index+"/shipinCurStudy"+index+".aspx";
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	try {
    		response = instance.sendHttpGet(httpClient, heads, path, this.proxyInfo);
    		int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
    			this.referer = path;
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinCurStudy 请求成功---->status="+status);
    			this.shipinSection(user);
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinCurStudy 请求失败---->status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinCurStudy 请求异常");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void shipinSection(User user) {
		String path = this.prefixUrl + "/StudentClass"+index+"/shipinSection"+index+".aspx";
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	try {
    		response = instance.sendHttpGet(httpClient, heads, path, this.proxyInfo);
    		int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
    			this.referer = path;
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinSection -get-->请求成功---->status="+status);
    			HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				
				Element parm1 = document.getElementById("__EVENTTARGET");
				this.__EVENTTARGET = parm1.attr("value");
				
				Element parm2 = document.getElementById("__EVENTARGUMENT");
				this.__EVENTARGUMENT = parm2.attr("value");
				
				Element parm3 = document.getElementById("__VIEWSTATE");
				this.__VIEWSTATE = parm3.attr("value");
				
				Element parm4 = document.getElementById("__VIEWSTATEGENERATOR");
				this.__VIEWSTATEGENERATOR = parm4.attr("value");
				this.CheckCanWatch(user);
				
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinSection-get--> 请求失败---->status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinSection-get-->请求异常");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void CheckCanWatch(User user) {
		String path = this.prefixUrl + "/StudentClass"+index+"/shipinSection"+index+".aspx/CheckCanWatch?dt="+ SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
		
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("application/json; charset=UTF-8");
	    heads.setxRequestedWith("XMLHttpRequest");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setOrigin(this.origin);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	
    	int i = user.getNowNum();
		String id = i <10 ? "0000" + i : "000" + i;
		this.ids = id;
		String params = "{Vcode:\"" + id + "\"}";
    	try {
			response = instance.sendHttpPost(httpClient, heads, path, params, this.proxyInfo);
			int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
    			String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
    			String d = (String) JSONObject.fromObject(resMsg).get("d");
    			if("".equals(d)) {
    				this.referer = path;
        			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频 -CheckCanWatch 请求成功---->status="+status);
        			Header[] hearders = response.getHeaders("Set-Cookie");
        			String rid = hearders[0].getValue();
    				this.RID = rid.substring(0, rid.indexOf(";"));
    				this.shipinSectionPost(user);
    			}else {
    				resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-CheckCanWatch---->d="+d);
    				if("您今天的课时已学完，请明日再学！每日正常学时不超过8节。".equals(d)) {
    					resultMap.put("successFlag", "1");
    					resultMap.put("dayNum", "9");
    				}
    				return;
    			}
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-CheckCanWatch 请求失败---->status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-CheckCanWatch->请求异常");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void shipinSectionPost(User user) {
		String path = this.prefixUrl + "/StudentClass"+index+"/shipinSection"+index+".aspx";
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("application/x-www-form-urlencoded");
	    heads.setxRequestedWith("XMLHttpRequest");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setOrigin(this.origin);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	int classNo = user.getNowNum();
    	Map<String, String> maps = new HashMap<String, String>();
    	maps.put("__EVENTTARGET", this.__EVENTTARGET);
		maps.put("__EVENTARGUMENT", this.__EVENTARGUMENT);
        maps.put("__VIEWSTATE", this.__VIEWSTATE); 
        maps.put("__VIEWSTATEGENERATOR",this.__VIEWSTATEGENERATOR);
        maps.put("dr1","-1");
        for(int k=0;k<10;k++) {
        	String key = "rep1$ctl0"+ k +"$hdOrders";
        	maps.put(key, "2");
    		if(classNo%10 != 0) {
    			if((k+1)==(classNo%10)) {
    				maps.put("rep1$ctl0"+k+"$Button1", "进入听课");
    			}
    		}else {
    			if(k == 9) {
    				maps.put("rep1$ctl09$Button1", "进入听课");
    			}
    		}
        }
        try {
        	response = instance.sendHttpPost(httpClient, heads, path, maps, proxyInfo);
        	int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinSection -post--> 请求成功");
    			this.watchVideo(user);
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinSection -post--> 请求失败status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinSection -post-->请求异常");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void watchVideo(User user){
		String path = this.prefixUrl + "/StudentClass"+index+"/WatchVideo"+index+".aspx?ids="+this.ids;
		this.cookie = this.cookie + "; " + this.RID + "; id=" + this.ids;
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setReferer(this.referer);
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	try {
    		response = instance.sendHttpGet(httpClient, heads, path, proxyInfo);
    		int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
				this.referer = path;
				resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-watchVideo 请求成功---->status="+status);
				this.saveUpdateInfo(user);
				//updateStudyVideo(user);
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-watchVideo 请求失败---->status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-watchVideo 请求失败");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void saveUpdateInfo(User user) {
		Study study = new Study();
		//设置开始听课时间
		String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(0);
		st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
		int totaltime = this.getTotalTime(nowNum);
		int nowtime = totaltime - (int)(25+Math.random()*(50-25+1));
		
		String path = this.prefixUrl + "/StudentClass"+index+"/WatchVideo"+index+".aspx/UpdateStudyType?dt=" + SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
		String params = "{RVCode:\"" + this.ids + "\"}";
		this.cookie = this.cookie + "; totaltime="+totaltime +"; url="+SpecialCharacterHandler.replaceAll(referer) +"; checkUid="+userid.split("=")[1] +"; st="+st 
					+"; PC1=%u6210%u529F; PC2=%u6210%u529F; PC3=%u6210%u529F; PC4=%u6210%u529F; nowtime="+nowtime;
		
		study.setCode(user.getCode());
		study.setCookie(cookie);
		study.setUrl(path);
		study.setUid(user.getId());
		study.setCreateTime(new Date());
		study.setParams(params);
		study.setSuccessFlag(0);
		study.setNum(nowNum);
		study.setZyName(user.getZyName());
		study.setIp(this.proxyInfo);
		resultMap.put("study", study);
		resultMap.put("successFlag", "1");
		resultMap.put("msg",user.getZyName() +"-"+ user.getCode() +"-第"+nowNum +"个视频保存听课信息成功");
		
	}
	
	public Map<String,Object> updateStudyVideo(Study study,String ip) {
		resultMap = new ConcurrentHashMap<>();
		resultMap.put("successFlag", "0");
		resultMap.put("dayNum", "0");
		resultMap.put("addNum", "0");
		resultMap.put("status", "1");
		this.nowNum = study.getNum();
		//设置开始听课时间
		String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(0);
		st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
		String params = study.getParams();
		String path = study.getUrl();
		String cookie = study.getCookie();
		
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("application/json, text/javascript, */*; q=0.01");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("application/json; charset=UTF-8");
	    heads.setCookie(cookie);
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	heads.setxRequestedWith("XMLHttpRequest");
    	try {
			response = instance.sendHttpPost(httpClient, heads, path, params, ip);
			int status = response.getStatusLine().getStatusCode();
			String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			String msg = (String) JSONObject.fromObject(entityStr).get("d");
    		if(status == 200) {
    			resultMap.put("successFlag", "1");
    			if("进度更新完毕，请看下个视频".equals(msg)){
					resultMap.put("dayNum", "1");
					resultMap.put("addNum", "1");
				}else if("本视频播放完毕".equals(msg)){
					resultMap.put("addNum", "1");
				}else if("课程全部看完，可以进行考试".equals(msg)){
					resultMap.put("dayNum", "1");
					resultMap.put("addNum", "1");
					resultMap.put("status", "3");
				}else {
					resultMap.put("msg", study.getZyName()+"-"+study.getCode() +"-第"+nowNum+"个视频-updateStudyVideo---->msg="+msg);
					return resultMap;
				}
				resultMap.put("msg", study.getZyName()+"-"+study.getCode() +"-第"+nowNum+"个视频-updateStudyVideo 请求成功---->msg="+msg);
    		}else {
    			resultMap.put("msg", study.getZyName()+"-"+study.getCode() +"-第"+nowNum+"个视频-updateStudyVideo 请求失败---->status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", study.getZyName()+"-"+study.getCode() +"-第"+nowNum+"个视频-updateStudyVideo 请求失败");
		}finally {
			instance.closeResource(response, httpClient);
		}
    	return resultMap;
	}
	
	
	public void updateStudyVideo(User user) {
		//设置开始听课时间
		String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(0);
		st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
		int nowNum = user.getNowNum();
		int totaltime = this.getTotalTime(nowNum);
		int nowtime = totaltime - (int)(25+Math.random()*(50-25+1));
		
		String path = this.prefixUrl + "/StudentClass"+index+"/WatchVideo"+index+".aspx/UpdateStudyType?dt=" + SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
		String params = "{RVCode:\"" + this.ids + "\"}";
		this.cookie = this.cookie + "; totaltime="+totaltime +"; url="+SpecialCharacterHandler.replaceAll(referer) +"; checkUid="+userid.split("=")[1] +"; st="+st 
					+"; PC1=%u6210%u529F; PC2=%u6210%u529F; PC3=%u6210%u529F; PC4=%u6210%u529F; nowtime="+nowtime;
		
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("application/json, text/javascript, */*; q=0.01");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("application/json; charset=UTF-8");
	    heads.setCookie(this.cookie);
    	heads.setHost(this.host);
    	heads.setOrigin(this.origin);
    	heads.setReferer(this.referer);
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	heads.setxRequestedWith("XMLHttpRequest");
    	try {
			response = instance.sendHttpPost(httpClient, heads, path, params, this.proxyInfo);
			int status = response.getStatusLine().getStatusCode();
			String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			String msg = (String) JSONObject.fromObject(entityStr).get("d");
			System.out.println(entityStr);
    		if(status == 200) {
    			if("进度更新完毕，请看下个视频".equals(msg)){
					resultMap.put("dayNum", "1");
					resultMap.put("addNum", "1");
				}else if("本视频播放完毕".equals(msg)){
					resultMap.put("addNum", "1");
				}else if("课程全部看完，可以进行考试".equals(msg)){
					user.setStatus(3);
				}else {
					resultMap.put("msg", user.getZyName()+"-"+user.getCode() + "-updateStudyVideo---->msg="+msg);
					return;
				}
				resultMap.put("msg", user.getZyName()+"-"+user.getCode() + "-updateStudyVideo 请求成功---->msg="+msg);
    		}else {
    			resultMap.put("msg", user.getZyName()+"-"+user.getCode() + "-updateStudyVideo 请求失败---->status="+status);
    		}
		} catch (Exception e) {
			resultMap.put("msg", user.getZyName()+"-"+user.getCode() + "-updateStudyVideo 请求失败");
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	private int getTotalTime(int i) {
		switch(i){
			case 1:return 2458;
			case 2:return 2318;
			case 3:return 2349;
			case 4:return 2421;
			case 5:return 2409;
			case 6:return 2367;
			case 7:return 2281;
			case 8:return 2483;
			case 9:return 2417;
			case 10:return 2418;
			case 11:return 2382;
			default : return 2458;
		}
	}
}
